<template>
  <div class="add-edit-user-view" v-loading="loading">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item :label="$t('tables_title.account')" prop="account" v-if="!isEdit">
        <el-input v-model="ruleForm.account" :placeholder="$t('tables_title.account')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.name')" prop="name">
        <el-input v-model="ruleForm.name" :placeholder="$t('tables_title.name')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.birthday')" prop="birthday">
        <el-date-picker v-model="ruleForm.birthday" type="date" :placeholder="$t('tables_title.birthday')" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('tables_title.password')" prop="password" v-if="!isEdit">
        <el-input v-model="ruleForm.password" :placeholder="$t('tables_title.password')" type="password"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.repeat_password')" prop="password2" v-if="!isEdit">
        <el-input v-model="ruleForm.password2" :placeholder="$t('tables_title.repeat_password')" type="password"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.email')" prop="email">
        <el-input v-model="ruleForm.email" :placeholder="$t('tables_title.email')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.sex')" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="M">{{$t('tables_title.male')}}</el-radio>
          <el-radio label="W">{{$t('tables_title.female')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('tables_title.phone')" prop="phone">
        <el-input v-model="ruleForm.phone" :placeholder="$t('tables_title.phone')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.dept')" prop="deptName">
        <div class="deptname-input" @click="innerVisible = true"></div>
        <el-input v-model="ruleForm.deptName" :placeholder="$t('tables_title.dept')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tables_title.position')" prop="position">
        <el-select v-model="position" multiple :placeholder="$t('tables_title.position')">
          <el-option
            v-for="item in positions"
            :key="item.positionId"
            :label="item.name"
            :value="item.positionId">
          </el-option>
        </el-select>
      </el-form-item>
      <div style="text-align: center;">
        <el-button type="primary" @click="submitForm('ruleForm')">{{$t('global.submit')}}</el-button>
        <el-button @click="cancelView">{{$t('global.cancel')}}</el-button>
      </div>
    </el-form>

    <el-dialog width="350px" :visible.sync="innerVisible" append-to-body>
        <div class="user-tree-view">
          <div class="user-tree-data-view">
            <el-tree :data="treeData" :props="treeProps" node-key="id" default-expand-all :expand-on-click-node="false"
            @node-click="handleNodeClick"></el-tree>
          </div>
          <div style="text-align: center;">
            <el-button @click="innerVisible = false">{{$t('global.cancel')}}</el-button>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>

import { getPositionList } from '@/api/positionApi.js'
import { addMgrUser,editMgrUser } from '@/api/userApi.js'

export default {
  data(){
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('user_management.pwd_again')));
      } else if (value !== this.ruleForm.password) {
        callback(new Error(this.$t('user_management.pwd_inconsistent')));
      } else {
        callback();
      }
    };
    return{
      loading:false,
      sex:0,
      innerVisible:false,
      positions: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      position:[],
      ruleForm:{
        account:'',
        name:'',
        birthday:'',
        password:'',
        password2:'',
        email:'',
        sex:'M',
        phone:'',
        deptId:'',
        deptName:'',
        position:''
      },
      rules:{
          account: [
            { required: !this.isEdit, message: this.$t('user_management.empty_account'), trigger: 'blur' },
          ],
          name: [
            { required: true, message: this.$t('user_management.empty_name'), trigger: 'blur' },
          ],
          password: [
            { required: !this.isEdit, message: this.$t('user_management.empty_password'), trigger: 'blur' },
            { min: 6, max: 14, message: this.$t('user_management.pwd_condition'), trigger: 'blur' }
          ],
          password2: [
            { validator: validatePass, trigger: 'blur' }
          ],
          email: [
            { required: true, message: this.$t('user_management.empty_email'), trigger: 'blur' },
            { type: 'email', message: this.$t('user_management.email_error'), trigger: ['blur', 'change'] }
          ],
          deptName: [
            { required: true, message: this.$t('user_management.empty_dept'),trigger: ['blur', 'change']},
          ],
      }
    }
  },
  props: ["isEdit",'editUserInfo',"treeData"],
  components:{

  },
  watch:{
    editUserInfo(newVal,oldVal){
      this.ruleForm = newVal
      this.ruleForm.sex = this.ruleForm.sex?this.ruleForm.sex:'M'
    }
  },
  created(){
    this.ruleForm = this.editUserInfo
    this.ruleForm.sex = this.ruleForm.sex?this.ruleForm.sex:'M'
    this.getPositionInfoList()
  },
  methods:{
    getPositionInfoList(){        //获取职位列表
      getPositionList().then((res)=>{
        this.positions = res.data.data
      }).catch((e)=>{

      })
    },
    handleNodeClick(data){      //树形节点点击触发事件
      this.ruleForm.deptId = data.id
      this.ruleForm.deptName = data.name
      this.innerVisible = false
    },
    submitForm(formName) {
      this.ruleForm.position = this.position.join(",")
      console.log(this.ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = new FormData()
          formData.append("account",this.ruleForm.account)
          formData.append("name",this.ruleForm.name)
          formData.append("birthday",this.ruleForm.birthday || '')
          formData.append("password",this.ruleForm.password)
          formData.append("email",this.ruleForm.email)
          formData.append("sex",this.ruleForm.sex)
          formData.append("phone",this.ruleForm.phone)
          formData.append("deptId",this.ruleForm.deptId)
          formData.append("deptName",this.ruleForm.deptName)
          formData.append("position",this.ruleForm.position)
          if(this.ruleForm.userId){
            formData.append("userId",this.ruleForm.userId)
            this.editUser(formData)
          }else{
            this.addUser(formData)
          }
        } else {
          return false;
        }
      });
    },
    editUser(formData){         //修改用户信息
      this.loading = true
      editMgrUser(formData).then((res)=>{
        this.loading = false
        console.log(res)
        if(res.data.code == 200){
          this.$message({
            message: this.$t('global.modified_success'),
            type: 'success'
          });
          this.refreshData()
        }else{
          this.$message.error(res.data.message)
        }
      }).catch((e)=>{

      })
    },
    addUser(formData){          //新增管理员
      this.loading = true
      console.log(this.ruleForm)
      addMgrUser(formData).then((res)=>{
        this.loading = false
        if(res.data.code == 200){
          this.$message({
            message: this.$t('global.added_success'),
            type: 'success'
          });
          this.refreshData()
        }else{
          this.$message.error(res.data.message)
        }
      }).catch((e)=>{

      })
    },
    cancelView(){       //关闭弹窗
      this.$emit('cancelView')
    },
    refreshData(){
      this.$emit('refreshData')
    }
  }
}
</script>

<style lang="scss" scoped>
.add-edit-user-view{
  width: 100%;
  min-height: 500px;
  box-sizing: border-box;
  padding-right: 30px;
  padding-left: 30px;
}

.el-select{
  width: 100%;
}

.user-tree-view{
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
  .user-tree-data-view{
    flex: 1;
    width: 100%;
    overflow: auto;
    margin-bottom: 10px;
  }
}
</style>
